package com.ramos.kuaixiao.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.ramos.kuaixiao.entity.Customer;

public class CustomerWareHouseDB {
    private static String TAG = "CustomerWareHouseDB";
    private static String TABLE_NAME = "CustomerWareHouse";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "CustomerId" + " CHAR(30)," + "CustomerName" + " CHAR(30)," + "WareHouseList" + " CHAR(500));";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    /* 向数据库中添加数据
    * @param name
    * @param age
    * @param sex
    * @param whichclass
    */
    public int addShop(Customer customer) {
        Log.d(TAG, "addShop " + customer.getName());
        if (hasCustomer(customer)) {
            updateCustomer(customer);
            return 1;
        } else {
            SQLiteDatabase db = DBHelper.open();
            db.execSQL("insert into CustomerWareHouse(CustomerId,CustomerName,WareHouseList) values(?,?,?)",
                    new Object[]{customer.getId(), customer.getName(), customer.getWareHouseList()});
            return 0;
        }
    }


    public void updateCustomer(Customer customer) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("update CustomerWareHouse set WareHouseList = ? where CustomerId=? and CustomerName=?",
                new Object[]{customer.getWareHouseList(), customer.getId(), customer.getName()});
    }

    public boolean hasCustomer(Customer customer) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from CustomerWareHouse where CustomerId =? and CustomerName=?", new String[]{customer.getId(), customer.getName()});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasCustomer true");
            return true;
        } else {
            Log.d(TAG, "hasCustomer false");
            cursor.close();
            return false;
        }
    }


    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM CustomerWareHouse");
    }

    public String findCustomer(String customerId, String customerName) {
        Log.d(TAG, "findCustomer");
        String list = null;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from CustomerWareHouse where CustomerId =? and CustomerName=?", new String[]{customerId, customerName});
        if(cursor.moveToFirst()) {
            Log.d(TAG, "moveToFirst:"+list);
            list = cursor.getString(3);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findCustomer " + list);
        return list;
    }
}
